// file

#include <stdio.h>
#include "student.h"

void read(FILE* fp, int index);

int main(int argc, char const *argv[])
{
    // 在文件中定位
    // long ftel(FILE* stream);
    // int fseek(FILE* stream, long offset, int whence);
    // - SEEK_SET: 从头开始
    // - SEEK_CUR: 从当前位置开始
    // - SEEK_END: 从尾开始（倒过来）
    FILE* fp = fopen("student.data", "r");
    if (fp)
    {
        fseek(fp, 0L, SEEK_END);
        long size = ftell(fp);
        int number = size / sizeof(Student);
        int index = 0;
        printf("There are %d datas, which one do U want: \n", number);
        scanf("%d", &index);
        // 符合一般人数数从 1 开始的习惯（程序员气抖冷
        read(fp, index - 1);
        fclose(fp);
    }
    
    return 0;
}

void read(FILE* fp, int index)
{
    // 从头开始，第 index 个结构体
    fseek(fp, index * sizeof(Student), SEEK_SET);
    Student stu;
    if (fread(&stu, sizeof(Student), 1, fp) == 1)
    {
        printf("No. %d student\n", index + 1);
        printf("\tName: %s\n", stu.name);
        printf("\tGender: ");
        switch (stu.gender)
        {
            case 0:
                printf("Male\n");
                break;
        
            case 1:
                printf("Female\n");
                break;

            case 2:
                printf("Others\n");
                break;
        }
        printf("\tAge: %d\n", stu.age);
    }
}

// 这样的二进制文件不具有可移植性